package com.guinea.core;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import net.sf.navigator.menu.MenuRepository;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderServlet;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.guinea.core.service.CommonService;
import com.guinea.core.tag.DictEntry;


import ex.system.service.DictionaryServiceEx;
import ex.system.service.MenuServiceEx;

public class MyContextLoaderServlet extends ContextLoaderServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected static Logger logger = LoggerFactory.getLogger(MyContextLoaderServlet.class);

	public void init() throws ServletException {
        super.init();
        setupContext(getServletContext());
    }
    
    public static void setupContext(ServletContext context) {
		ApplicationContext ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);
		SessionFactory sessionFactory = (SessionFactory)ctx.getBean("sessionFactory");
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		MenuServiceEx menuServiceEx = (MenuServiceEx) ctx.getBean("menuServiceEx");
		MenuRepository repository = menuServiceEx.getRepository();
		MenuRepository defaultRepository = (MenuRepository) context
				.getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
		repository.setDisplayers(defaultRepository.getDisplayers());
		context.setAttribute("repository", repository);
		
		DictionaryServiceEx dictionaryServiceEx = (DictionaryServiceEx) ctx.getBean("dictionaryServiceEx");
		List dict = dictionaryServiceEx.get();
		context.setAttribute("dict", dict);
		
		CommonService commonService = (CommonService) ctx.getBean("commonService");
		
		List rsscs = commonService.getRsscs();
		context.setAttribute("rsscs", rsscs);
		List provinces = commonService.getProvinces();
		context.setAttribute("provinces", provinces);
		List cities = commonService.getCities();
		context.setAttribute("cities", cities);
		List districts = commonService.getDistricts();
		context.setAttribute("districts", districts);
		
		cities = DictEntry.assembleEntry(cities,districts);
		provinces = DictEntry.assembleEntry(provinces,cities);
		String pcdJson = DictEntry.convertEntryListToJson(provinces);;
		context.setAttribute("provincecitydistrict",pcdJson);
		
		tx.commit();
		
		logger.debug("<=========== Initialization complete [OK]");

	}
}
